﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace EasyStock
{
    public class CommonClass
    {
        public static Dictionary<string, Stock> dicStock;

        public static Dictionary<string, Stock> getStockByCode(string code)
        {
            WebClient myWebClient = new WebClient();
            string strAll = myWebClient.DownloadString("http://hq.sinajs.cn/list=" + code);
            string[] arrayStrStock = strAll.Split('\n');
            foreach (string str in arrayStrStock)
            {
                if (str == "")
                    continue;
                string strCode = str.Substring(str.LastIndexOf('_') + 1, str.IndexOf('=') - str.LastIndexOf('_') - 1);
                int start = str.IndexOf('"') + 1;
                int length = str.LastIndexOf('"') - str.IndexOf('"') - 1;
                string strStock = str.Substring(start, length);
                if (strStock == "")
                    continue;
                string[] array = strStock.Split(',');

                Stock sto = new Stock();
                sto.Code = strCode;
                sto.StockName = array[0];
                sto.Openning = array[1];
                sto.Close = array[2];
                sto.NowPrice = array[3];
                sto.MaxPrice = array[4];
                sto.MinPrice = array[5];
                sto.Volume = array[8];
                sto.TotalPrice = array[9];
                sto.Date = array[30];
                sto.Time = array[31];
                dicStock.Add(strCode, sto);
            }
            return dicStock;
        }

        public static List<KeyValuePair<string, Stock>> dicSort(string type, int style)
        {
            try
            {
                switch (type)
                {
                    case "Code":
                        if (style == 0) { return dicStock.OrderByDescending(d => d.Value.Code).ToList(); }
                        else { return dicStock.OrderBy(d => d.Value.Code).ToList(); }
                    case "Volume":
                        if (style == 0) { return dicStock.OrderByDescending(d => int.Parse(d.Value.Volume)).ToList(); }
                        else { return dicStock.OrderBy(d => int.Parse(d.Value.Volume)).ToList(); }
                }
            }
            catch { }
            return null;
        }
    }
}
